/*
 * @(#) $CVSHeader:  $
 *
 * Copyright (C) 2010 by Netcetera AG.
 * All rights reserved.
 *
 * The copyright to the computer program(s) herein is the property of
 * Netcetera AG, Switzerland.  The program(s) may be used and/or copied
 * only with the written permission of Netcetera AG or in accordance
 * with the terms and conditions stipulated in the agreement/contract
 * under which the program(s) have been supplied.
 *
 * @(#) $Id: FeedItemViewActivity.java 95 2010-07-11 18:06:26Z lpancevski $
 */
package com.dreamcode.anfeedreader.activity;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dreamcode.anfeedreader.collectors.FeedsDAOimpl;
import com.dreamcode.anfeedreader.collectors.SettingsDAOimpl;
import com.dreamcode.anfeedreader.modelClass.AccountObject;
import com.dreamcode.anfeedreader.modelClass.FeedItem;
import com.dreamcode.anfeedreader.utils.BitlyAndroid;
import com.facebook.android.Facebook;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.types.FacebookType;


public class FeedItemViewActivity extends Activity {
  
  private TextView content = null;
  private TextView contentDate = null;
  private TextView bodyText = null;
  private FeedsDAOimpl feedsDAO = null;
  private Button webViewBtn = null;
  private Button backBtn = null;
  private Button markBtn = null;
  private Button shareBtn = null;
  private LinearLayout lineLayout = null;
  private WebView webView = null;
  private Twitter twitter = null;
  private AccessToken accessToken = null;
  private AccountObject accountObject = null;
  private SettingsDAOimpl settingsDAO = null;
  private static final String CONSUMER_KEY = "ZyuteDnOzt4pIld95iPugQ";
  private static final String CONSUMER_SECRET = "9tRFCaPvrYJ8jLKTAvnjFfK93OENw1FSpL9hkO89r0";
  private BitlyAndroid bitly = null;  
  private FeedItem contentItem = null;
  private Facebook facebook = null;
  private FacebookClient facebookClient = null;
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.feeditemview);
    initView();
  }

  private void initView() {
    feedsDAO = FeedsDAOimpl.getInstance(); 
    settingsDAO = SettingsDAOimpl.getInstance();
    content = (TextView) findViewById(R.id.item_view_title);
    content.setTextColor(Color.WHITE);
    contentDate = (TextView) findViewById(R.id.item_view_date);
    contentDate.setTextColor(Color.WHITE);
    bodyText = (TextView) findViewById(R.id.item_view_text);
    bodyText.setTextColor(Color.WHITE);
    lineLayout = (LinearLayout) findViewById(R.id.feedsline);
    lineLayout.setBackgroundColor(Color.BLACK);
    Bundle bundle = getIntent().getExtras();
    webView = (WebView) findViewById(R.id.webshow);
    final int feedItem_id = bundle.getInt("id");
    
    markBtn = (Button) findViewById(R.id.btnmark);
    markBtn.setOnClickListener(new OnClickListener() {
      
      @Override
      public void onClick(View arg0) {
        feedsDAO.changeStatusToMarked(FeedItemViewActivity.this,feedItem_id);
        Toast.makeText(FeedItemViewActivity.this, (CharSequence)Html.fromHtml(getString(R.string.marked_feeditem)), Toast.LENGTH_LONG).show();
      }
    });
    webViewBtn = (Button) findViewById(R.id.btnwebview);
    webViewBtn.setOnClickListener(new OnClickListener() {
        
        @Override
        public void onClick(View v){
                Intent i = new Intent(FeedItemViewActivity.this,FeedItemWebViewActivity.class);
                i.putExtra("id", feedItem_id);
                startActivity(i);
                finish();
        }
    });
    
    backBtn = (Button) findViewById(R.id.btnback);
    backBtn.setOnClickListener(new OnClickListener() {
        
        @Override
        public void onClick(View v){
                finish();
        }
    });
    shareBtn = (Button) findViewById(R.id.btnshare);
    shareBtn.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			LinearLayout holder = new LinearLayout(FeedItemViewActivity.this);
			holder.setOrientation(LinearLayout.VERTICAL);
			Button fbButton = new Button(FeedItemViewActivity.this);
			fbButton.setText("Facebook");
			if((settingsDAO.getAccoutSettings(FeedItemViewActivity.this, "Facebook"))==null)
			    fbButton.setEnabled(false);
			fbButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					statusDialog(contentItem.getLink(),1);
					
				}
			});
			Button twButton = new Button(FeedItemViewActivity.this);
			twButton.setText("Twitter");
			if((settingsDAO.getAccoutSettings(FeedItemViewActivity.this, "Twitter"))==null)
			    twButton.setEnabled(false);
			twButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					statusDialog(contentItem.getLink(),0);
				}
			});
			holder.addView(fbButton);
			holder.addView(twButton);			
			Builder shareDialog = new AlertDialog.Builder(FeedItemViewActivity.this);
			shareDialog.setView(holder).setTitle("Share Channel").setPositiveButton("OK", null).show();		
						
		}
	});
    
    
    contentItem = feedsDAO.getFeedItemDetail(FeedItemViewActivity.this, feedItem_id);
    if (contentItem != null) {
    	if(contentItem.getStatus().equals("0")){
    		List<String> itemForUpdate = new LinkedList<String>();
    		itemForUpdate.add(String.valueOf(contentItem.getId()));
    		itemForUpdate.add("1");
    		feedsDAO.updateFeedItem(FeedItemViewActivity.this, itemForUpdate);
    	}
        content.setText("Title: " + contentItem.getTitle());
        contentDate.setText("Date: " + contentItem.getPubDate()+"\n");
        if(contentItem.getDescription()!=null && (contentItem.getDescription().contains("<div")||contentItem.getDescription().contains("<img")))
            webView.loadData(contentItem.getDescription(), "text/html", "UTF-8");
        else        
            bodyText.setText("Description: " + ((contentItem.getDescription()!=null)?contentItem.getDescription():""+"\n"));
    }
  }

  
  
  
  public void statusDialog(final String url, final int type){
	LinearLayout statusHolder = new LinearLayout(FeedItemViewActivity.this);
	statusHolder.setGravity(Gravity.CENTER);
  	final EditText editStatus = new EditText(FeedItemViewActivity.this);
  	//editStatus.setGravity(Gravity.CENTER);
  	editStatus.setHint("Status");
  	editStatus.setWidth(200);
  	statusHolder.addView(editStatus);
  	
  	Builder statusBuilder = new AlertDialog.Builder(FeedItemViewActivity.this);
  	statusBuilder.setView(statusHolder).setTitle("Social Feed Sharing")
  	.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {					
					try {
						bitly = new BitlyAndroid("anfeedreader","R_d65746196608b9c5d7d41f66f0bc7974");
						String shortUrl = bitly.getShortUrl(url);
						switch(type){
							case 0:
								twitter = new TwitterFactory().getInstance();
								accountObject = (AccountObject)settingsDAO.getAccoutSettings(FeedItemViewActivity.this, "Twitter");
								twitter.setOAuthConsumer(CONSUMER_KEY,CONSUMER_SECRET);	
								accessToken = new AccessToken(accountObject.getAccessToken(),accountObject.getAccessSecret());
								twitter.setOAuthAccessToken(accessToken);									
								twitter.updateStatus(editStatus.getText().toString().concat(" "+shortUrl));								
								break;
							case 1:
								accountObject = (AccountObject)settingsDAO.getAccoutSettings(FeedItemViewActivity.this, "Facebook");
								facebookClient = new DefaultFacebookClient(accountObject.getAccessToken());								
								facebookClient.publish("me/feed", FacebookType.class,Parameter.with("message", editStatus.getText().toString()),Parameter.with("link", shortUrl));


								/*Bundle parameters = new Bundle();
								parameters.putString("message",editStatus.getText().toString());								
								parameters.putString("link",shortUrl);								
								facebook = new Facebook();
								facebook.setAccessToken(accountObject.getAccessToken());
								facebook.request("me/feed", parameters);*/
								break;
							default: break;						
						}
												
						Toast.makeText(FeedItemViewActivity.this, "The News is successful shared", Toast.LENGTH_SHORT).show();
						dialog.dismiss();
					} catch (TwitterException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}					
					
				}
			}).setNegativeButton("Cancel", null).show();
  	
	 }   
  
}
